package com.zhaopin.controller;

import com.zhaopin.entity.User;
import com.zhaopin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/userRedis")
public class UserRedisController {

    @Autowired
    private UserService userService;

    @PostMapping("add")
    //正常业务时， 需要在user类里面进行事务控制，控制层一般不进行业务控制的。
    //@Transactional(rollbackFor = Exception.class)
    public Map<String, String> addUser(@RequestBody User userReq) {

        User user = new User();
        user.setAddress(userReq.getAddress());
        user.setUsername(userReq.getUsername());
        //由于设置了主键策略 id可不用赋值 会自动生成
        //user.setId(0L);
        userService.add(user);
        Map<String, String> result = new HashMap<String, String>();
        result.put("respCode", "01");
        result.put("respMsg", "新增成功");
        //事务测试
        //System.out.println(1/0);
        return result;
    }

    @PostMapping("update")
    //更新时 直接删除缓存 以保证下次获取时先从数据库中获取最新数据
    @CacheEvict(value = "OKONG", key = "#userReq.id")
    public Map<String, String> updateUser(@RequestBody User userReq) throws Exception {

        if (userReq.getId() == null || "".equals(userReq.getId())) {
            throw new Exception("0000" + "更新时ID不能为空");
        }
        User user = new User();
        user.setAddress(userReq.getAddress());
        user.setUsername(userReq.getUsername());
        user.setId(userReq.getId());
        userService.update(user);
        Map<String, String> result = new HashMap<String, String>();
        result.put("respCode", "01");
        result.put("respMsg", "更新成功");
        return result;
    }

    @GetMapping("/get/{id}")
    @Cacheable(value = "OKONG", key = "#id")
    public Map<String, Object> getUser(@PathVariable("id") String id) throws Exception {
        //查询
        User user = userService.getUserById(Integer.parseInt(id));
        if (user == null) {
            throw new Exception("0001" + "用户ID：" + id + "，未找到");
        }
        User resp = User.builder()
                .id(user.getId())
                .address(user.getAddress())
                .name(user.getUsername())
                .build();
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("respCode", "01");
        result.put("respMsg", "成功");
        result.put("data", resp);
        return result;
    }


}